package com.lry.basic.algorithm.floodfill;

//leetcode 130
public class NumOfEnclaves2 {

    public void solve(char[][] grid) {
        if(null==grid||grid.length==0) return;

        //第一行和最后一行
        for(int i=0;i<grid[0].length;i++){
            dfs(grid,0,i);
            dfs(grid,grid.length-1,i);
        }

        //第一列和最后一列
        for(int i=0;i<grid.length;i++){
            dfs(grid,i,0);
            dfs(grid,i,grid[0].length-1);
        }

        for(int i=0;i<grid.length;i++){
            for(int j=0;j<grid[0].length;j++){
                if(grid[i][j]=='O'){
                    grid[i][j] = 'X';
                }
                if(grid[i][j]=='Y'){
                    grid[i][j] = 'O';
                }
            }
        }
    }

    private void dfs(char[][] grid,int i,int j){
        if(i<0||i>grid.length-1||j<0||j>grid[0].length-1||grid[i][j]!='O'){
            return ;
        }
        grid[i][j] = 'Y';
        dfs(grid,i+1,j);
        dfs(grid,i-1,j);
        dfs(grid,i,j+1);
        dfs(grid,i,j-1);
    }


    public static void main(String[] args) {
        char[][]c = new char[][]{{'X','X','X','X'}, {'X','O','O','X'}, {'X','X','O','X'}, {'X','O','O','X'}};
        new NumOfEnclaves2().solve(c);
        for(int i=0;i<c.length;i++){
            for(int j=0;j<c[0].length;j++){
                System.out.print(c[i][j]+" ");
            }
            System.out.println();
        }
    }

}
